﻿using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SmartFrame_DataCollect.Forms
{
    public partial class frmService : XtraForm
    {
        string serviceFilePath = AppDomain.CurrentDomain.BaseDirectory+ @"DataCollectService\DataCollectService.exe";
        string serviceName = "";
        ServiceController curServiceController = null;
        SmartFrame_DataCollect.Tasks frmTask = null;
        public frmService(SmartFrame_DataCollect.Tasks _frmTask)
        {
            InitializeComponent();
            InitServiceStatus();
            frmTask = _frmTask;
        }

        /// <summary>
        /// 初始化服务状态
        /// </summary>
        public void InitServiceStatus()
        {
            serviceName = lblServiceName.Text;
            if(IsServiceExisted(serviceName))
            {
                lblStatus.Text = "已创建";
                if(curServiceController.Status ==  ServiceControllerStatus.Running)
                {
                    lblStatus.Text = "运行中";
                }
                else
                {
                    lblStatus.Text = "已停止";
                }
            }
            else
            {
                lblStatus.Text = "未创建";
            }
        }

        //判断服务是否存在
        private bool IsServiceExisted(string serviceName)
        {
            ServiceController[] services = ServiceController.GetServices();
            foreach (ServiceController sc in services)
            {
                if (sc.ServiceName.ToLower() == serviceName.ToLower())
                {
                    curServiceController = sc;
                    return true;
                }
            }
            return false;
        }

        //安装服务
        private void InstallService(string serviceName,string serviceFilePath)
        {
            StringBuilder installCMD = new StringBuilder();
            installCMD.AppendLine(@"chcp 65001");
            installCMD.AppendLine(@"@echo.请稍等，服务启动......");
            installCMD.AppendLine(@"@echo off");
            installCMD.AppendLine(@"@sc create " + serviceName + " binPath= \"" + serviceFilePath + "\"");
            installCMD.AppendLine(@"@net start " + serviceName + "");
            installCMD.AppendLine(@"@sc config " + serviceName + "  start= AUTO");
            installCMD.AppendLine(@"@sc description " + serviceName + " 汇创H6采集服务");
            installCMD.AppendLine(@"@echo off");
            installCMD.AppendLine(@"@echo.启动完毕！");
            installCMD.AppendLine(@"@pause");

            File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + @"\DataCollectService\1.bat", installCMD.ToString());
            ExecBatCommand(AppDomain.CurrentDomain.BaseDirectory + @"\DataCollectService\1.bat");
        }

        /// <summary>
        /// 打开控制台执行拼接完成的批处理命令字符串
        /// </summary>
        /// <param name="inputAction">需要执行的命令委托方法：每次调用 <paramref name="inputAction"/> 中的参数都会执行一次</param>
        private static void ExecBatCommand(string filePath)
        {
            using (Process myPro = new Process())
            {
                myPro.StartInfo.FileName = filePath;
                myPro.StartInfo.UseShellExecute = false;
                myPro.StartInfo.CreateNoWindow = false;
                myPro.Start();
                myPro.WaitForExit();
            }
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            //已创建服务
            if (IsServiceExisted(serviceName))
            {
                XtraMessageBox.Show("已创建该服务器");
            }
            else
            {
                //服务地址
                InstallService(serviceName, serviceFilePath);
                InitServiceStatus();
                //初始化服务对象数据
                Thread threadRunSignalR = new Thread(() =>
                {
                    //5秒后初始化数据
                    Thread.Sleep(5000);
                    frmTask.InitConnection(true);
                });
                threadRunSignalR.Start();

            }
        }

        private void simpleButton2_Click(object sender, EventArgs e)
        {
            //已创建服务
            if (!IsServiceExisted(serviceName))
            {
                XtraMessageBox.Show("请先创建该采集服务");
            }
            else
            {
                if (curServiceController.Status == ServiceControllerStatus.Running)
                {
                    XtraMessageBox.Show("该服务已经在运行");
                }
                else
                {
                    curServiceController.Start();
                    //初始化服务对象数据
                    Thread threadRunSignalR = new Thread(() =>
                    {
                        //5秒后初始化数据
                        Thread.Sleep(5000);
                        frmTask.InitConnection(true);
                    });
                    threadRunSignalR.Start();
                    Thread.Sleep(2000);
                    InitServiceStatus();
                }
            }
        }

        private void simpleButton3_Click(object sender, EventArgs e)
        {
            //已创建服务
            if (!IsServiceExisted(serviceName))
            {
                XtraMessageBox.Show("请先创建该采集服务");
            }
            else
            {
                if (curServiceController.Status == ServiceControllerStatus.Stopped)
                {
                    XtraMessageBox.Show("该服务已经停止");
                }
                else
                {
                    curServiceController.Stop();
                    InitServiceStatus();
                }
            }
        }

        private void simpleButton4_Click(object sender, EventArgs e)
        {
            InitServiceStatus();
        }
    }
}
